package org.essilab.analyzer.wikitionary;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.essilab.analyzer.analyzer.ITemplate;
import org.essilab.analyzer.analyzer.Term;
import org.essilab.analyzer.util.Language;
import org.essilab.analyzer.wikitionary.tags.FindTag;

/**
 * This class is used to fill the properties of a Term object parsing the
 * associated text content of the word.
 *
 * @author Mohamed-Amine Chouchene, Ahcène Idinarere, Vincent Nock, Alain
 * Janin-Manificat
 */
public class TemplateWiki implements ITemplate {

    @Override
    public void process(Term term, String text) {
        if (null != text && !text.trim().isEmpty()) {
            String[] lines = text.split("\n");
            for (int i = 0; i < lines.length; i++) {
                String line = lines[i].trim();
                if (!line.isEmpty() && line.startsWith("{{")) {
                    if (!FindTag.addType(term, line, subText(lines, i + 1))) {
                        FindTag.addRelation(term, line, subText(lines, i + 1));
                    }
                } else {
                    if (line.startsWith("==")) {
                        Pattern _p = Pattern.compile("== \\{\\{=([a-zA-Z]{2,})=\\}\\} ==", Pattern.CASE_INSENSITIVE);
                        Matcher _m = _p.matcher(line);
                        if (_m.find()) {
                            if (!_m.group(1).equals(Language.FRENCH) && !_m.group(1).equals("conv")) {
                                break;
                            }
                        }
                    }
                }

            }
        }
    }

    /**
     * Get the paragraphe in text at the given start index until the next EOL.
     *
     * @param text String - text to look in.
     * @param start int - start index
     * @return String - the paragraphe that begin at start index and end at the
     * next EOL.
     */
    private String subText(String[] text, int start) {
        String str = "";
        if (text.length > start && text[start].trim().equals("{{(}}")) {
            boolean first = false;
            for (int i = start; i < text.length; i++) {
                if (!text[i].trim().equals("{{)}}")) {
                    if (first) {
                        str += "\n";
                    } else {
                        first = true;
                    }
                    str += text[i];
                } else {
                    break;
                }
            }
        } else {
            boolean first = false;
            for (int i = start; i < text.length; i++) {
                if (!text[i].trim().isEmpty()) {
                    if (first) {
                        str += "\n";
                    } else {
                        first = true;
                    }
                    str += text[i];
                } else {
                    break;
                }
            }
        }
        return str;
    }
}